﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using Amazon.SimpleDB.Util;

using PennyStorm.Util;

namespace PennyStormAuctionTimer
{    
    class Program
    {        
        static void UpdateItem(object obj)
        {
            string id = (string)obj;
            
            int currentTime = 0;
            int newTime = 0;            
            AmazonSimpleDBFactory.Instance.ConsistentSwapInteger(id, Properties.Settings.Default.item_TimeKey, false, 1, out currentTime, out newTime);

            Console.WriteLine("Original time-- {0}, new time {1}", currentTime, newTime);

            if (newTime == 0)
            {
                AmazonSimpleDBFactory.Instance.SetIntegerValue(id, Properties.Settings.Default.item_ActiveKey, 0);
            }
        }

        static void Main(string[] args)
        {
            SelectRequest select = new SelectRequest();
            select.SelectExpression = "SELECT * from PennyStorm_Items WHERE active='1'";

            using (AmazonSimpleDBClient sdb = new AmazonSimpleDBClient(Properties.Settings.Default.key, Properties.Settings.Default.secret))
            {

                try
                {
                    while (true)
                    {
                        DateTime start = DateTime.Now;

                        //
                        // Get all auctions
                        //
                        List<Item> results = Program.GetAllResults(sdb, select);
                        Console.WriteLine("Number of active items: {0}", results.Count);
                        //
                        // Wait until 1 second has passed
                        //
                        DateTime stop = DateTime.Now;
                        TimeSpan elapsedTime = stop - start;

                        double sleepTime = (1.00 - elapsedTime.TotalSeconds) < 0 ? 0 : 1.00 - elapsedTime.TotalSeconds;
                        int milisecondsSleepTime = Convert.ToInt32((sleepTime * 1000));

                        if (milisecondsSleepTime > 0)
                        {
                            Console.WriteLine("Sleeping for {0}", milisecondsSleepTime);
                            System.Threading.Thread.Sleep(milisecondsSleepTime);
                        }

                        foreach (Item item in results)
                        {
                            //
                            // Update the time for each item; pop each one into a thread pool so we can do this as quickly as possible
                            //
                            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(UpdateItem), item.Name);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                }
            }
        }

        public static List<Item> GetAllResults(AmazonSimpleDBClient sdb, SelectRequest select)
        {
            List<Item> results = new List<Item>();
             
            do
            {
                SelectResponse response = sdb.Select(select);                

                //
                // Get the complete list
                //
                foreach (Item item in response.SelectResult.Item)
                {
                    results.Add(item);
                }

                //
                // Get the next set
                //
                select.NextToken = response.SelectResult.NextToken;                

            } while (select.NextToken != null);

            return results;
        }
    }
}
